﻿using IPS.SP2013.DiagnosticsProvider;
using Microsoft.SharePoint.Administration;
using System;

namespace IPS.SP2013.Helper
{

    /// <summary>
    /// 
    /// </summary>
    public static class IPSWebAppHelper
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="webApp"></param>
        /// <param name="zone"></param>
        /// <param name="defaultLoginPage"></param>
        /// <param name="relativeLoginUrl"></param>
        public static void SetCustomLoginPage(ref SPWebApplication webApp, SPUrlZone zone, 
                                              bool defaultLoginPage = false, string relativeLoginUrl = "")
        {
            try
            {
                if (webApp != null)
                {
                    // Update login mapped page
                    webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.Login, relativeLoginUrl);
                    
                    //Get IIS settings for specific zone
                    SPIisSettings iisSettings =  webApp.GetIisSettingsWithFallback(zone);
                    
                    if (iisSettings != null)
                    {
                        // Set custom login page
                        if (defaultLoginPage)
                        {
                            iisSettings.ClaimsAuthenticationRedirectionUrl = null;
                        }
                        else
                        {
                            iisSettings.ClaimsAuthenticationRedirectionUrl = new Uri(relativeLoginUrl, UriKind.Relative);
                        }
                    }
                    else
                    {
                        LogProvider.WriteLogEntry(DiagnosticsProvider.Constants.CategoryNames.Warning,
                                                  "IPSWebAppHelper.SetCustomLoginPage(): Unable to get IIS settings from current web application in zone " + zone.ToString());
                    }

                    webApp.Update(true);
                }
                else
                {
                    LogProvider.WriteLogEntry(DiagnosticsProvider.Constants.CategoryNames.Warning,
                                              "IPSWebAppHelper.SetCustomLoginPage(): Unable to get web application");
                }
            }
            catch (Exception ex)
            {
                LogProvider.WriteLogEntry(DiagnosticsProvider.Constants.CategoryNames.Error, 
                                          "IPSWebAppHelper.SetCustomLoginPage(): " + ex.Message);
                throw;
            }
        }

    }

}
